<template>
  <div>
    <div class="topSearch" v-if="showBtn">
      <p>
        <el-input size="small" style="width: 200px" placeholder="按店铺名称搜索" clearable
                  v-model="params.storeName"></el-input>
      </p>
      <p>
        <el-select clearable size="small" style="width: 200px" placeholder="按品牌搜索" v-model="params.systemType">
          <el-option v-for="(a,i) in systemList" :value="a.id" :label="a.systemName" :key="i"></el-option>
        </el-select>
      </p>
      <p>
        <el-select size="small" style="width: 200px" placeholder="请选择付款方式" clearable v-model="params.paymentMethod">
          <el-option
              v-for="(item, index) in payTypeList"
              :key="index"
              :label="item.name"
              :value="item.id"
          ></el-option>
        </el-select>
      </p>
      <p>
        <el-date-picker
            type="date"
            size="small"
            clearable
            v-model="params.paymentTime"
            style="width: 200px;"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
        </el-date-picker>
      </p>
      <el-radio-group v-model="checkboxGroup1" size="small" style="float: right;margin-bottom: 2px"
                      @change="getHuikuanStatus">
        <el-radio-button v-for="(e, i) in huikuanStatus" :label="e.value" :key="i">{{ e.name }}</el-radio-button>
      </el-radio-group>
      <p style="margin-left: 15px">
        <el-button size="small" type="primary" @click="_search">搜 索</el-button>
        <el-button size="small" type="info" @click="_reset">重 置</el-button>
        <el-button size="small" type="success" @click="_otherAdd">新增回款</el-button>
      </p>
    </div>
    <div class="centerTable">
      <div v-if="showBtn">
        <el-button size="mini" type="info" @click="getStatus(0)">未到账</el-button>
        <el-button size="mini" type="primary" @click="getStatus(1)">已到账</el-button>
      </div>

      <!--      showBtn     材料订单列表 点击金额查看回款明细  公用页面-->
      <el-table
          :data="collectData" border
          :height="showBtn?'calc(100vh - 240px)':'auto'"
          v-loading="loading"
          :cellStyle="{ textAlign: 'center', 'font-size': '14px' }"
          :headerCellStyle="{
          textAlign: 'center',

          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
          fontSize: '13px'
        }"
      >
        <el-table-column type="index" label="序号" width="60px"></el-table-column>
        <el-table-column prop="serialNumber" label="流水号" width="100px" show-overflow-tooltip></el-table-column>
        <el-table-column prop="systemName" v-if="checkboxGroup1!=7" label="品牌" width="180px"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="storeName" v-if="checkboxGroup1!=7" label="店铺名称" width="180px"
                         show-overflow-tooltip></el-table-column>
        <!--        <el-table-column label="订单类型" width="180px" show-overflow-tooltip>-->
        <!--          <template v-slot:default="scope">-->
        <!--            <span> {{ scope.row.orderType == 1 ? '新增单' : '补货单' }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="业务类型" width="180px" show-overflow-tooltip>
          <template v-slot:default="scope">
            <span>{{ huikuanStatus.find(item => item.value === checkboxGroup1).name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentTime" label="收款时间"></el-table-column>
        <el-table-column prop="amount" label="收款金额"></el-table-column>
        <el-table-column prop="paymentMethodName" label="收款方式"></el-table-column>
        <el-table-column prop="prove" label="收款凭证">
          <template v-slot:default="scope">
            <el-image v-if="scope.row.prove" style="width: 15px;height:15px;margin-left: 15px"
                      v-for="item in scope.row.prove.split(',')"
                      :src="'https://'+item" :key="item"
                      :preview-src-list="scope.row.prove.split(',').map(a=>'https://'+a)"></el-image>
          </template>

        </el-table-column>

        <el-table-column v-if="params.type==7" prop="description" label="描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="creatorName" label="创建人"></el-table-column>
        <el-table-column prop="payState" label="状态">
          <template v-slot:default="scope">
            <span v-if="scope.row.payState==0" style="color: #ff4949">未到账</span>
            <span v-if="scope.row.payState==1" style="color: #13ce66">已入账</span>
          </template>
        </el-table-column>
        <el-table-column prop="a" label="操作" v-if="showBtn">
          <template v-slot:default="scope">
            <el-link style="font-size: 13px"
                     v-if="authority.includes(241)"
                     type="primary" @click="collect(scope.row)">
              确认到账
            </el-link>
            <el-link style="font-size: 13px;margin-left: 15px"
                     v-if="authority.includes(241)"
                     type="warning" @click="_editList(scope.row)">
              编辑
            </el-link>
            <el-link style="font-size: 13px;margin-left: 15px"
                     v-if="authority.includes(241)"
                     type="danger" @click="_deleteList(scope.row)">
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          style="padding: 20px 0"
          align="right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[200, 300,]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
      >
      </el-pagination>
    </div>
    <el-dialog :visible.sync="otherDialog" center title="新增其他回款" width="35%" top="50px">
      <div class="otherBox">
        <p><span>回款金额：</span>
          <el-input v-model="other.amount" placeholder="请输入回款金额" size="small" style="width: 250px"></el-input>
        </p>
        <p><span>备 注：</span>
          <el-input v-model="other.description" placeholder="请输入" size="small" style="width: 250px"></el-input>
        </p>
        <p><span>收款方式：</span>
          <el-select v-model="other.paymentMethod" placeholder="请选择" size="small" style="width: 250px">
            <el-option
                v-for="(item, index) in payTypeList"
                :key="index"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>

        </p>
        <p><span>回款时间：</span>
          <el-date-picker
              type="date"
              size="small"
              v-model="other.paymentTime"
              placeholder="请选择时间
           "
              value-format="yyyy-MM-dd"
              style="width: 250px"
          ></el-date-picker>
        </p>
        <p style="width: 55%">
          <span>回款凭证：</span>
        </p>
        <el-upload
            class="upload-demo"
            drag
            :headers="headers"
            :action="`${$apiHost}/common/fileImgUrl`"
            :on-success="onSuccess"
            :show-file-list="false"
            :on-remove="_delete"
            multiple>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传/支持复制粘贴上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
        <div style="display: flex;">
          <p v-for="(item,index) in proof">
            <el-image :src="'https://'+item" style="width: 35px;height: 35px"
                      :preview-src-list="proof.map((a)=>'https://'+a)"></el-image>
            <span @click="_delete(index)"
            ><el-icon class="el-icon-delete" style="font-size: 14px"></el-icon
            ></span>
          </p>
        </div>
      </div>
      <span slot="footer">
        <el-button size="small" type="info" @click="otherDialog=false">取 消</el-button>
        <el-button size="small" type="success" @click="submitOther">提 交</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="editDilog" center title="编辑" width="35%" top="50px">
      <div class="otherBox">
        <p><span>回款金额：</span>
          <el-input v-model="editObj.amount" placeholder="请输入回款金额" size="small" style="width: 250px"></el-input>
        </p>
        <p><span>收款方式：</span>
          <el-select v-model="editObj.paymentMethod" placeholder="请选择" size="small" style="width: 250px">
            <el-option
                v-for="(item, index) in payTypeList"
                :key="index"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>

        </p>
        <p><span>回款时间：</span>
          <el-date-picker
              type="date"
              size="small"
              v-model="editObj.paymentTime"
              placeholder="请选择时间
           "
              value-format="yyyy-MM-dd"
              style="width: 250px"
          ></el-date-picker>
        </p>
        <p v-if="editObj.type==7"><span>描述：</span>
          <el-input v-model="editObj.description" placeholder="请输入描述文字" size="small" style="width: 250px"></el-input>
        </p>
      </div>
      <span slot="footer">
        <el-button size="small" type="info" @click="editDilog=false">取 消</el-button>
        <el-button size="small" type="success" @click="submitEdit">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import store from "../../store";

export default {
  name: "collectList",
  props: {
    showBtn: {
      type: Boolean,
      default: true
    },
    collectName: {
      type: String,
      default: ''
    },
  },
  computed: {
    headers() {
      return {
        token: this.token || window.$quinn.getStorage('token'),
      }
    },
  },
  data() {
    return {
      editObj: {
        id: "",
        paymentMethod: "",
        description: "",
        paymentTime: "",
        amount: "",
        type: "",
      },
      collectData: [],
      other: {},
      checkboxGroup1: 2,
      otherDialog: false,
      editDilog: false,
      loading: false,
      authority: [],
      huikuanStatus: [
        {value: 1, name: '货架'},
        {value: 2, name: '材料'},
        {value: 3, name: '洞洞板'},
        {value: 4, name: '新增单'},
        {value: 5, name: '赵一鸣收银台,背景墙'},
        {value: 6, name: '扩容升级'},
        {value: 7, name: '其他回款'},
      ],
      payTypeList: [],
      systemList: [],
      proof: [],
      totalCount: 0,
      currentPage: 1,
      params: {
        pageSize: 200,
        pageNumber: 1,
        type: 2,
        storeName: "",
        paymentMethod: "",
        systemType: "",
        paymentTime: '',
      }
    }
  },
  created() {
    const {authorityList = []} = this.$quinn.getStorage('userData') || {}
    this.authority = authorityList
    this.getList()
    this.getSystemType()
    this.getPayType()
    document.addEventListener('paste', this.handlePaste)
  },
  methods: {
    _editList(row) {
      this.editDilog = true
      this.editObj.id = row.paymentId
      this.$api.paymentPaymentView({id: row.paymentId}).then(res => {
        // 用解构合并，减少循环
        Object.assign(this.editObj, {
          ...this.editObj,
          ...res
        })
        this.editObj.type = row.type
      })
    },
    submitEdit() {
      this.$api.paymentEditPayment(this.editObj).then(res => {
        if (res == 1) {
          this.$message('编辑成功！')
          this.editDilog = false
          this.getList()
        }
      })
    },
    async _deleteList(row) {
      // /payment/deletePayment
      const r = await this.$confirm("确认删除吗？", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch(() => null);
      if (r) {
        const res = await this.$api.paymentDeletePayment({id: row.paymentId}).catch(() => null);
        if (res == 1) {
          this.$message.success('操作成功!')
          this.getList()
        }
      }
    }
    ,
    submitOther() {
      const data = {
        ...this.other,
        type: 7,
        prove: this.proof.join(',')
      }
      this.$api.paymentAddOtherPayment(data).then(res => {
        if (res) {
          this.$message.success('提交成功！')
          this.otherDialog = false
          this.getList()
        }
      })
    }
    ,
    onSuccess(res) {
      if (res.code === 200 && res.result) {
        this.proof.push(res.result[0])
      }
    }
    ,
    handlePaste(event) {
      if (!this.otherDialog) return;
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i];

          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            if (file) {
              this.uploadImage(file);
            }
          } else {
            break;
          }
        }
      }
    }
    ,
    deletePaiedUrl(i) {
      // this.editableTabs[this.tabIndex - 1].data.fileList.splice(i, 1)
      this.proof.splice(i, 1)
    }
    ,
    uploadImage(imageFile) {
      const formData = new FormData();
      formData.append('file', imageFile);
      axios.post(`${this.$apiHost}/common/fileImgUrl`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token': store.state.token
        }
      })
          .then(response => {
            this.proof.push(response.data.result[0]);
          })
          .catch(error => {
          });
    }
    ,
    _delete(index) {
      this.proof.splice(index, 1)
    }
    ,
    _otherAdd() {
      this.otherDialog = true
      this.other = this.$options.data.call(this).other
      this.proof = []
    }
    ,
    getHuikuanStatus(val) {
      this.params.pageNumber = 1
      this.params.type = val
      this.getList()
    }
    ,
    async getPayType() {
      const res = await this.$api.orderGetPaymentMethod()
      if (res && res.length) {
        this.payTypeList = []
        this.payTypeList = res
      }
    }
    ,
    async getSystemType() {
      const res = await this.$api.orderGetSystemTypeVo()
      this.systemList = res
    }
    ,
    _reset() {
      this.params = this.$options.data.call(this).params
    }
    ,
    getList() {
      this.loading = true
      const data = this.params
      if (this.collectName) {
        this.params.storeName = this.collectName
      }
      this.$api.orderGetPaymentList(data).then(res => {
        this.collectData = res.data
        this.totalCount = res.total
        this.loading = false
      })
    }
    ,
    _search() {
      this.params.pageNumber = 1
      this.getList()
    }
    ,
    handleSizeChange(val) {
      this.params.pageSize = val
      this.getList()
    }
    ,
    getStatus(val) {
      this.params.payState = val
      this.getList()
    }
    ,
    handleCurrentChange(val) {
      this.params.pageNumber = val
      this.getList()
    }
    ,
    collect(row) {
      this.$confirm(`确认 ${row.storeName} 回款单已成功到账？`, '提示', {
        confirmButtonText: '通过',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--success',
        cancelButtonClass: 'el-button--danger',
      })
          .then(() => {
            this.$api.orderUpdatePaymentPayState({paymentId: row.paymentId}).then(res => {
              if (res == 1) {
                this.$message.success("操作成功！")
                this.getList()
              }
            })
          })
          .catch((action) => {
          });
    }
  },
}
</script>

<style scoped lang="less">
.otherBox {
  display: flex;
  flex-direction: column;
  align-items: center;

  p {
    margin-bottom: 15px;
  }

  span {
    display: inline-block;
    width: 80px;
  }
}

.topSearch {
  display: flex;
  margin-bottom: 10px;

  p {
    margin-right: 15px;
  }
}

</style>